package bb.lanxing.activity.bluetooth;

import java.util.Objects;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseDisplayActivity;
import bb.lanxing.activity.HeartrateSectionSettingActivity;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.databinding.unit.UnitConstants;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.api.ConnectionListener;
import bb.lanxing.lib.devices.api.DeviceManager;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.ble.BleCons;
import bb.lanxing.lib.devices.ble.heartrate.HeartRateBeltController;
import bb.lanxing.lib.devices.core.utils.CharacteristicValueHelper;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.model.database.Device;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.shape.ShapeUtils;
import bb.lanxing.view.BiciAlertDialogBuilder;
import bb.lanxing.view.dialog.HeartRateSelectDialog;
import gov.nist.core.Separators;

public class HeartRateBeltStatusActivity extends BaseDisplayActivity implements ConnectionListener {
    private static final String TAG = "HeartRateBeltStatusActivity";
    private static final String x1Hr = "xoss_x1";
    private static final String x2Hr = "xoss_x2";
    private static final String hrmPro = "hrmpro";
    private String address;
    private Device device;
    private HeartRateBeltController heartRateBeltController;
    private ImageView imageViewHeader;
    private Button mBtnUnbind;
    private TextView mFtvBattery;
    private TextView mFtvHeartRate;
    private RelativeLayout mRlHeartRateSection;
    private RelativeLayout mRlStatusHeartRate;
    private RelativeLayout mRlWarnHeartRate;
    private TextView mTvName;
    private TextView mTvWarnHeartRate;
    private String selectHR;
    private Switch warningSwitch;
    private boolean isTypeXoss = false;
    private boolean isSensorLocationSet = false;
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (Objects.requireNonNull(action)) {
            case BleCons.ACTION_HEARTRATE_BODY_LOCATION_RESULT -> {
                int intExtra = intent.getIntExtra(BleCons.ACTION_HEARTRATE_BODY_LOCATION_DATA, -1);
                if (intExtra == 4) {
                    setTitle(R.string.device_heartrate_belt_title);
                    imageViewHeader.setImageResource(R.drawable.ic_default);
                } else if (intExtra == 1) {
                    setTitle(R.string.device_heartrate_title);
                    if (device.getName().toLowerCase().contains(x2Hr)) {
                        imageViewHeader.setImageResource(R.drawable.ic_default);
                    } else if (device.getName().toLowerCase().contains(x1Hr)) {
                        imageViewHeader.setImageResource(R.drawable.ic_default);
                    }
                }
            }
            case BleCons.ACTION_HERATRATE_BELT_WARN_SET_STATUS -> {
                mRlHeartRateSection.setVisibility(View.VISIBLE);
                mRlStatusHeartRate.setVisibility(View.VISIBLE);
                warningSwitch.setChecked(intent.getBooleanExtra(BleCons.EXTRA_HERATRATE_BELT_WARN_SET_STATUS, false));
                if (selectHR != null) {
                    TextView textView = mTvWarnHeartRate;
                    textView.setText(selectHR + UnitConstants.UNIT_BPM);
                }
            }
            case "ACTION_BATTERY" -> {
                int deviceType = intent.getIntExtra("EXTRA_DEVICE_TYPE", 0);
                if (deviceType == SmartDevice.TYPE_HEARTRATE_BELT || deviceType == SmartDevice.TYPE_HEARTRATE) {
                    int intExtra3 = intent.getIntExtra("EXTRA_BATTERY", 0);
                    mFtvBattery.setText(intExtra3 + Separators.PERCENT);
                    if (device.getName().toLowerCase().contains(hrmPro)) {
                        imageViewHeader.setImageResource(R.drawable.ic_default);
                    } else {
                        requestHeartRateBodyLocation();
                    }
                }
            }
            case BleCons.ACTION_HERATRATE_BELT_WARN -> {
                mRlHeartRateSection.setVisibility(View.VISIBLE);
                mRlStatusHeartRate.setVisibility(View.VISIBLE);
                String stringExtra = intent.getStringExtra(BleCons.EXTRA_HERATRATE_BELT_WARN);
                warningSwitch.setChecked(intent.getBooleanExtra(BleCons.EXTRA_HERATRATE_BELT_WARN_STATUS, false));
                mTvWarnHeartRate.setText(stringExtra + UnitConstants.UNIT_BPM);
            }
            case BleCons.ACTION_HERATRATE_BELT_WARN_CLOSE_STATUS -> {
                mRlHeartRateSection.setVisibility(View.VISIBLE);
                mRlStatusHeartRate.setVisibility(View.VISIBLE);
                if (intent.getBooleanExtra(BleCons.EXTRA_HERATRATE_BELT_WARN_CLOSE_STATUS, false)) {
                    warningSwitch.setChecked(false);
                }
            }
            default -> {
            }
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (this.device.getName().toLowerCase().contains(x2Hr)) {
            this.imageViewHeader.setImageResource(R.drawable.ic_default);
        } else if (this.device.getName().toLowerCase().contains(x1Hr)) {
            this.imageViewHeader.setImageResource(R.drawable.ic_default);
        }
        if (!DeviceHelper.isConnected(this.device.getAddress())) {
            DeviceHelper.connect(this.device);
            return;
        }
        requestBattery();
        requestHRAlertState();
    }

    public void requestBattery() {
        this.mFtvHeartRate.postDelayed(() -> {
            Intent intent = new Intent(BleCons.ACTION_REQUEST_BATTERY);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE,
                    isTypeXoss ? SmartDevice.TYPE_HEARTRATE : SmartDevice.TYPE_HEARTRATE_BELT);
            intent.putExtra(CharacteristicValueHelper.EXTRA_ADDRESS, device.getAddress());
            sendOrderedBroadcast(intent, null);
        }, 100L);
    }

    public void requestHRAlertState() {
        this.mFtvHeartRate.postDelayed(() -> {
            heartRateBeltController = XZDeviceHelper.getHeartRateController();
            if (heartRateBeltController != null) {
                heartRateBeltController.initWarnHr();
                Log.e(TAG, "initWarnHr()");
                return;
            }
            Log.e(TAG, "heartRateBeltController null");
        }, 600L);
    }

    public void requestHeartRateBodyLocation() {
        if (!this.isSensorLocationSet) {
            this.isSensorLocationSet = true;
            Intent intent = new Intent(BleCons.ACTION_HEARTRATE_BODY_LOCATION);
            intent.putExtra(BleCons.EXTRA_DEVICE_TYPE,
                    this.isTypeXoss ? SmartDevice.TYPE_HEARTRATE : SmartDevice.TYPE_HEARTRATE_BELT);
            intent.putExtra(CharacteristicValueHelper.EXTRA_ADDRESS, this.device.getAddress());
            sendOrderedBroadcast(intent, null);
        }
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_heart_rate_belt_status);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        DeviceHelper.registerConnectionStateListener(this);
        registerReceiver();
        Device byAddress = Device.getByAddress(getIntent().getStringExtra(BleCons.EXTRA_DEVICE_ADDRESS));
        this.device = byAddress;
        if (byAddress == null) {
            finish();
            return;
        }
        this.mTvName.setText(byAddress.getName());
        if (this.device.getName().toLowerCase().contains("xoss")) {
            this.isTypeXoss = true;
        }
        ShapeUtils.shape(this).line(2, R.color.color_fe4545).radius(4.0f).into(this.mBtnUnbind);

        this.warningSwitch.setOnClickListener(view -> {
            if (!warningSwitch.isChecked()) {
                heartRateBeltController.closeWarnHr();
            } else {
                showSelectHR();
            }
        });

        this.warningSwitch.setOnCheckedChangeListener(
                (compoundButton, z) -> mRlWarnHeartRate.setVisibility(z ? View.VISIBLE : View.GONE));
    }

    private void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_unbind) {
            unBoundDeviceConfirm();
        } else if (id == R.id.rl_heart_rate_section) {
            startActivity(new Intent(this, HeartrateSectionSettingActivity.class));
        } else if (id == R.id.rl_warn_heart_rate) {
            showSelectHR();
        }
    }

    private void unBoundDeviceConfirm() {
        new BiciAlertDialogBuilder(this).setTitle(R.string.st_forget_sensor).setMessage(R.string.st_are_you_sure_unbind)
                .setPositiveButton(R.string.mine_profile_dialog_btn_unbind, (dialogInterface, i) -> {
                    if (device.getDeviceNumber() > 0) {
                        MyHttpClient.deleteDevice(device.getDeviceNumber());
                    }
                    Device.deleteAll(Device.class, "address = ? and userId = ?", device.getAddress(),
                            String.valueOf(App.getContext().getUserId()));
                    if (isTypeXoss) {
                        App.getContext().disconnectDevice(SmartDevice.TYPE_HEARTRATE_BELT);
                    }
                    DeviceContext.startAndRefreshAutoConnector();
                    finish();
                }).setNegativeButton(R.string.str_sync_cancel, (dialogInterface, i) -> {
                }).show().setCanceledOnTouchOutside(true);
    }

    public void showSelectHR() {
        String[] strArr = new String[181];
        int i = 50;
        for (int i2 = 0; i2 < 181; i2++) {
            strArr[i2] = (i2 + 60) + " ";
            if (mTvWarnHeartRate.getText().toString().replace(UnitConstants.UNIT_BPM, "").equals(strArr[i2])) {
                i = i2 + 1;
            }
        }
        final HeartRateSelectDialog heartRateSelectDialog = new HeartRateSelectDialog(this, strArr);
        heartRateSelectDialog.setCanceledOnTouchOutside(false);
        heartRateSelectDialog.select(i);
        heartRateSelectDialog.show();

        heartRateSelectDialog.findViewById(R.id.tv_sprint_watchface_confirm).setOnClickListener(view -> {
            heartRateBeltController.setWarnHr(Integer.parseInt(heartRateSelectDialog.getSelectHR()));
            selectHR = heartRateSelectDialog.getSelectHR();
            heartRateSelectDialog.dismiss();
        });
    }

    @Override
    public void onDestroy() {
        DeviceHelper.unregisterConnectionStateListener(this);
        BroadcastReceiver broadcastReceiver = this.broadcastReceiver;
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        super.onDestroy();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleCons.ACTION_BATTERY);
        intentFilter.addAction(BleCons.ACTION_HEARTRATE_DATAS);
        intentFilter.addAction(BleCons.ACTION_HERATRATE_BELT_WARN);
        intentFilter.addAction(BleCons.ACTION_HERATRATE_BELT_WARN_SET_STATUS);
        intentFilter.addAction(BleCons.ACTION_HERATRATE_BELT_WARN_CLOSE_STATUS);
        intentFilter.addAction(BleCons.ACTION_HEARTRATE_BODY_LOCATION_RESULT);
        registerReceiver(broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
    }

    private void uploadDeivceInfo() {
        MyHttpClient.uploadDevice(new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str) {
                try {
                    device.setDeviceNumber(new JSONObject(str).getInt("deviceServerId"));
                    device.save();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, this.device);
    }

    @Override
    protected void onRefreshUI(DisplayPoint displayPoint) {
        this.mFtvHeartRate.setText(String.valueOf(displayPoint.getHeartrate(0)));
    }

    private void bindView(View view) {
        this.mTvName = (TextView) view.findViewById(R.id.tv_name);
        this.imageViewHeader = (ImageView) view.findViewById(R.id.img);
        this.mFtvHeartRate = (TextView) view.findViewById(R.id.ftv_heart_rate);
        this.mFtvBattery = (TextView) view.findViewById(R.id.ftv_battery);
        this.mTvWarnHeartRate = (TextView) view.findViewById(R.id.tv_warn_heart_rate);
        this.mRlWarnHeartRate = (RelativeLayout) view.findViewById(R.id.rl_warn_heart_rate);
        this.mRlHeartRateSection = (RelativeLayout) view.findViewById(R.id.rl_heart_rate_section);
        this.mRlStatusHeartRate = (RelativeLayout) view.findViewById(R.id.rl_status_heart_rate);
        this.mBtnUnbind = (Button) view.findViewById(R.id.btn_unbind);
        this.warningSwitch = (Switch) view.findViewById(R.id.warningSwitch);

        this.mBtnUnbind.setOnClickListener(this::onClick);

        this.mRlWarnHeartRate.setOnClickListener(this::onClick);

        this.mRlHeartRateSection.setOnClickListener(this::onClick);
    }

    @Override
    public void onConnectionStateChanged(SmartDevice smartDevice, int i, int i2) {
        if (smartDevice.getAddress().equals(this.device.getAddress())) {
            if (i == DeviceManager.STATE_CONNECTED) {
                this.mFtvHeartRate.postDelayed(() -> {
                    requestBattery();
                    requestHRAlertState();
                }, 600L);
            } else if (i == DeviceManager.STATE_DISCONNECTED) {
                finish();
            }
        }
    }
}
